<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>多AI对话比较-单轮</title>
    <!-- 引入 highlight.js 样式 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github.min.css">
    <!-- 引入 marked.js 用于 Markdown 解析 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/4.2.12/marked.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
    <!-- 引入常用语言语法高亮 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/python.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/javascript.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/json.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/bash.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        h1 {
            margin-top: 0;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        .chat-container {
            display: flex;
            flex-direction: column;
            flex: 1;
            gap: 20px;
        }
        .input-area {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }
        #prompt {
            flex: 1;
            padding: 12px;
            font-size: 16px;
            border: 1px solid #ddd;
            border-radius: 4px;
            min-height: 20px;
            line-height: 1.5;
        }
        .prompt-select-area {
            display: flex;
            gap: 10px;
            align-items: center;
            margin-bottom: 15px;
        }
        #sysprompt-select {
            flex: 1;
            padding: 8px;
            font-size: 14px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            padding: 0 20px;
            font-size: 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            white-space: nowrap;
        }
        button:hover {
            background-color: #45a049;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .responses-container {
            display: flex;
            flex: 1;
            gap: 20px;
            min-height: 0;
        }
        .ai-response-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: #f9f9f9;
            overflow: hidden;
        }
        .ai-title {
            font-weight: bold;
            padding: 15px;
            background-color: #e9e9e9;
            border-bottom: 1px solid #ddd;
        }
        .ai-content {
            flex: 1;
            padding: 15px;
            overflow-y: auto;
            line-height: 1.6;
            background-color: white;
        }
    </style>
</head>
<body>
    <h1>多AI对话比较-单轮</h1>
    <div class="chat-container">
        <div class="input-area">
            <textarea id="prompt" placeholder="输入您的问题..." rows="3" autocomplete="off"></textarea>
            <button id="ask-button">提问</button>
        </div>

        <div class="prompt-select-area">
            <label for="sysprompt-select">系统提示词：</label>
            <select id="sysprompt-select">
                <option value="">-- 请选择提示词 --</option>
            </select>
        </div>

        <div class="responses-container">
            <div class="ai-response-container">
                <div class="ai-title">AI服务1</div>
                <div class="ai-content" id="ai1-response">等待问题...</div>
            </div>
            <div class="ai-response-container">
                <div class="ai-title">AI服务2</div>
                <div class="ai-content" id="ai2-response">等待问题...</div>
            </div>
            <div class="ai-response-container">
                <div class="ai-title">AI服务3</div>
                <div class="ai-content" id="ai3-response">等待问题...</div>
            </div>
        </div>
    </div>

    <script>
        // 配置 marked.js：支持换行和代码高亮
        marked.setOptions({
            breaks: true,
            highlight: function(code, lang) {
                if (lang && hljs.getLanguage(lang)) {
                    return hljs.highlight(code, { language: lang }).value;
                }
                return hljs.highlightAuto(code).value;
            }
        });

        // 页面加载时获取提示词列表
        document.addEventListener('DOMContentLoaded', function() {
            fetch('/prompts/', {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            })
            .then(response => {
                if (!response.ok) throw new Error('获取提示词失败');
                return response.json();
            })
            .then(data => {
                const select = document.getElementById('sysprompt-select');
                select.innerHTML = '';
                data.prompts?.forEach(item => {
                    const option = document.createElement('option');
                    option.value = item;
                    option.textContent = item;
                    select.appendChild(option);
                });
            })
            .catch(error => {
                console.error('加载提示词错误:', error);
                alert('提示词加载失败: ' + error.message);
            });
        });

        // 绑定事件
        document.getElementById('ask-button').addEventListener('click', askAI);
        document.getElementById('prompt').addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                askAI();
            }
        });

        // 提问主函数：并行调用三个独立接口
        function askAI() {
            const prompt = document.getElementById('prompt').value.trim();
            if (!prompt) return;

            const syspromptSelect = document.getElementById('sysprompt-select');
            const sysprompt = syspromptSelect.value;

            // 显示加载状态
            document.getElementById('ai1-response').textContent = "思考中...";
            document.getElementById('ai2-response').textContent = "思考中...";
            document.getElementById('ai3-response').textContent = "思考中...";

            // 禁用按钮
            const button = document.getElementById('ask-button');
            button.disabled = true;
            button.textContent = "查询中...";

            // 请求数据
            const requestData = { prompt, sysprompt };

            // 三个独立接口
            const urls = ['/chat_deepseek/', '/chat_gpt4o/', '/chat_qwen3_coder/'];

            // 使用 Promise.allSettled 确保即使某个失败，其他仍能显示
            Promise.allSettled([
                // 请求 AI1
                fetch(urls[0], {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    body: JSON.stringify(requestData)
                }).then(res => {
                    if (!res.ok) throw new Error(`HTTP ${res.status}`);
                    return res.json();
                }),

                // 请求 AI2
                fetch(urls[1], {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    body: JSON.stringify(requestData)
                }).then(res => {
                    if (!res.ok) throw new Error(`HTTP ${res.status}`);
                    return res.json();
                }),

                // 请求 AI3
                fetch(urls[2], {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    body: JSON.stringify(requestData)
                }).then(res => {
                    if (!res.ok) throw new Error(`HTTP ${res.status}`);
                    return res.json();
                })
            ])
            .then(results => {
                const ids = ['ai1-response', 'ai2-response', 'ai3-response'];
                results.forEach((result, index) => {
                    if (result.status === 'fulfilled') {
                        const data = result.value;
                        const content = typeof data === 'object' && data.response ? data.response : data;
                        processAndDisplayResponse(ids[index], content || '无响应内容');
                    } else {
                        processAndDisplayResponse(ids[index], `<span style="color:red">❌ ${escapeHtml(result.reason.message)}</span>`);
                    }
                });
            })
            .catch(error => {
                console.error('整体请求异常:', error);
                document.getElementById('ai1-response').innerHTML = '<p style="color:red">系统错误</p>';
                document.getElementById('ai2-response').innerHTML = '<p style="color:red">系统错误</p>';
                document.getElementById('ai3-response').innerHTML = '<p style="color:red">系统错误</p>';
            })
            .finally(() => {
                button.disabled = false;
                button.textContent = "提问";
            });
        }

        // 处理响应并渲染 Markdown
        function processAndDisplayResponse(elementId, content) {
            const element = document.getElementById(elementId);
            if (!content) {
                element.innerHTML = '<p><em>无响应</em></p>';
                return;
            }

            // 如果是字符串，直接解析 Markdown
            const html = marked.parse(String(content));
            element.innerHTML = html;
        }

        // 转义 HTML 防止 XSS
        function escapeHtml(unsafe) {
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // 获取 CSRF Token（适用于 Django）
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.startsWith(name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    </script>
</body>
</html>